var mysql = require("mysql");
var express = require("express");
var bodyParser =require("body-parser");
var router = express.Router();

var dbcomm = require('./util/dbcomm');
var util = require("util");

router.use(bodyParser.json());
router.use(bodyParser.urlencoded({extended:false}))

router.get("/fuck",function(req,res,next){
    res.redirect("../exam/jiaose.html")
    });
router.get("/showDep",function(req,res){
    
    dbcomm.query("select authorityid, roleid,menuid from sys_authority   ",function(err,data){
       
        dbcomm.query("select authorityid, roleid ,menuid from sys_authority   limit "+ (req.query.page - 1) * req.query.rows +","+req.query.rows+" ",function(err,ll){  
            
            
            var fenye = {
               total:data.length,
               rows:ll
             };
                res.send(fenye);
          })
       })
   });


   router.post("/saveDep",function(req,res){
   
    console.log(req.body);
    var body=req.body;
    var menuid=body.menuid;
    var shs = JSON.parse(menuid);
   
    console.log(shs);
     
    

    var sql1 = "";
    for(i=0;i<menuid.length;i++){
        
    }
    
   
       sql1=" insert into sys_authority(roleid,menuid)values(?,?) "
       dbcomm.query(sql1,[req.body.roleid,menuid],function(err,data){
        console.log(data); 
        if(err) throw err;
        
           
    })
    
    dbcomm.query("delete from sys_authority where authorityid not in (select a.* from (select distinct(authorityid) from sys_authority group by roleid,menuid) a) ",[body.roleid],function(err){
        if(err) throw err;
    })
    res.send({"msg":true})
    
})

router.get("/treecs",function(req,res){
    var sql = "select * from sys_menu";
    dbcomm.query(sql,function(err,data){
        if(err)throw err;
        else{
  
            res.send(findRows(-1,data))
        }
    })
  
  })
  
  
  /**
  * 判断当前节点是否存在子节点 
  */
  function isCheck(id,tt){
  var ist = false;
  for(var i = 0 ;i < tt.length;i++){
    if(id == tt[i].pmenuid){
      ist = true;
      break;
    }
  }
  return ist;;
  }
  
  function findRows(id,dt){
  var arr = [];
  for(var i = 0 ;i < dt.length;i++){				
    if(id == dt[i].pmenuid){
      var first= {
        id : dt[i].menuid,
        text : dt[i].menuname,
      }				
      if(isCheck(dt[i].menuid,dt)){
        first["children"] = findRows( dt[i].menuid,dt);
      }
      arr[arr.length] = first;
    }
  }
  return arr;		
  }



module.exports = router;